#!/bin/bash
# 服务器一键部署脚本（CentOS 7.x）
# 功能：系统初始化（交换内存+GCC）+ OpenSSL 1.1.1w + Python 3.11.9 + MySQL 8.0
# 执行：sudo ./server_onekey_deploy.sh

# -------------------------- 基础函数定义 --------------------------
# 1. 错误提示并退出
error_exit() {
    echo -e "\n❌ 错误：$1"
    exit 1
}

# 2. 进度提示
progress_msg() {
    echo -e "\n=== $1 ==="
}

# 3. 密码复杂度校验（返回0=符合，1=不符合）
check_password() {
    local pwd="$1"
    # 条件：8位以上 + 含大小写 + 含数字 + 含特殊字符（!@#$%^&*()）
    if [ ${#pwd} -lt 8 ]; then
        return 1
    elif ! echo "$pwd" | grep -qE '[A-Z]'; then
        return 1
    elif ! echo "$pwd" | grep -qE '[a-z]'; then
        return 1
    elif ! echo "$pwd" | grep -qE '[0-9]'; then
        return 1
    elif ! echo "$pwd" | grep -qE '[!@#$%^&*()?]'; then
        return 1
    else
        return 0
    fi
}

# 4. 交互输入MySQL信息（避免硬编码）
input_mysql_info() {
    progress_msg "请输入MySQL配置信息（将用于创建数据库和用户）"
    
    # 输入root密码（并校验）
    while true; do
        read -p "1. 输入MySQL root密码（要求：8位+大小写+数字+特殊字符）：" -s ROOT_PWD
        echo
        if check_password "$ROOT_PWD"; then
            break
        else
            echo "⚠️  密码不符合要求！请重新输入（例：Root@123）"
        fi
    done

    # 输入项目数据库名（默认order_db）
    read -p "2. 输入项目数据库名（默认：order_db）：" DB_NAME
    DB_NAME=${DB_NAME:-order_db}

    # 输入项目用户名（默认order_user）
    read -p "3. 输入项目数据库用户名（默认：order_user）：" DB_USER
    DB_USER=${DB_USER:-order_user}

    # 输入项目用户密码（并校验）
    while true; do
        read -p "4. 输入项目用户密码（要求同root密码）：" -s USER_PWD
        echo
        if check_password "$USER_PWD"; then
            break
        else
            echo "⚠️  密码不符合要求！请重新输入（例：User@456）"
        fi
    done

    # 确认信息
    echo -e "\n=== 确认MySQL配置 ==="
    echo "root密码：****（您输入的）"
    echo "项目数据库名：$DB_NAME"
    echo "项目用户名：$DB_USER"
    echo "项目用户密码：****（您输入的）"
    read -p "是否继续？（y/n）：" confirm
    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        error_exit "用户取消部署"
    fi
}

# -------------------------- 主部署流程 --------------------------
# 1. 校验root权限
if [ "$(id -u)" -ne 0 ]; then
    error_exit "请用root权限执行：sudo ./server_onekey_deploy.sh"
fi

# 2. 自动检测CPU核心数，动态设置编译线程数（核心优化点）
CPU_CORES=$(grep -c ^processor /proc/cpuinfo)
echo -e "\n检测到服务器CPU核心数：$CPU_CORES 核"

# 根据CPU核心数设置编译线程数（2核用2线程，4核及以上用4线程，1核用1线程）
if [ $CPU_CORES -ge 4 ]; then
    MAKE_JOBS=4
elif [ $CPU_CORES -eq 2 ]; then
    MAKE_JOBS=2
else
    MAKE_JOBS=1
fi
echo "自动设置编译线程数：make -j$MAKE_JOBS（适配当前CPU性能）"

# 3. 欢迎信息
echo -e "\n============================================="
echo "服务器一键部署脚本（CentOS 7.x）"
echo "功能：交换内存+GCC 9 + OpenSSL 1.1.1w + Python 3.11.9 + MySQL 8.0"
echo "============================================="
read -p "按回车键开始部署（预计10-15分钟）..."

# 4. 交互输入MySQL信息（敏感信息不硬编码）
input_mysql_info

# -------------------------- 模块1：系统初始化 --------------------------
progress_msg "模块1/4：系统初始化（交换内存+GCC 9+基础依赖）"

# 4.1 配置4GB交换内存（缓解2G小内存压力）
progress_msg "配置4GB交换内存（小内存服务器必备）"
dd if=/dev/zero of=/root/swapfile bs=1M count=4096 >/dev/null 2>&1 || error_exit "交换文件创建失败"
chmod 600 /root/swapfile || error_exit "交换文件权限设置失败"
mkswap /root/swapfile >/dev/null 2>&1 || error_exit "交换分区创建失败"
swapon /root/swapfile || error_exit "交换分区启用失败"
echo '/root/swapfile swap swap defaults 0 0' | tee -a /etc/fstab >/dev/null || error_exit "交换分区开机挂载配置失败"

# 4.2 升级GCC到9.x
progress_msg "升级GCC到9.x"
# 备份并配置yum仓库
mkdir -p /etc/yum.repos.d/backup || error_exit "yum仓库备份目录创建失败"
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ || error_exit "yum仓库备份失败"
curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo || error_exit "阿里云基础仓库下载失败"
# 配置SCL仓库（高版本GCC依赖）
cat > /etc/yum.repos.d/CentOS-SCLo-scl.repo << EOF
[centos-sclo-scl]
name=CentOS-7 - SCLo scl
baseurl=https://mirrors.aliyun.com/centos/7/sclo/x86_64/sclo/
gpgcheck=1
enabled=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-SIG-SCLo
EOF
cat > /etc/yum.repos.d/CentOS-SCLo-scl-rh.repo << EOF
[centos-sclo-scl-rh]
name=CentOS-7 - SCLo rh
baseurl=https://mirrors.aliyun.com/centos/7/sclo/x86_64/rh/
gpgcheck=1
enabled=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-SIG-SCLo
EOF
# 清理缓存+导入GPG密钥
yum clean all >/dev/null 2>&1
yum makecache fast >/dev/null 2>&1 || error_exit "yum缓存重建失败"
curl -o /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo https://www.centos.org/keys/RPM-GPG-KEY-CentOS-SIG-SCLo || error_exit "GPG密钥下载失败"
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo || error_exit "GPG密钥导入失败"
# 安装GCC 9
yum install -y centos-release-scl devtoolset-9-gcc devtoolset-9-gcc-c++ >/dev/null 2>&1 || error_exit "GCC 9安装失败"
# 配置GCC永久生效
echo "source /opt/rh/devtoolset-9/enable" >> ~/.bashrc || error_exit "GCC永久生效配置失败"
source ~/.bashrc || error_exit "GCC配置加载失败"
gcc_version=$(gcc --version | head -1 | awk '{print $3}')
echo "✅ GCC版本：$gcc_version"

# 4.3 安装基础依赖
progress_msg "安装系统基础依赖"
yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make libffi-devel perl-Test-Simple >/dev/null 2>&1 || error_exit "基础依赖安装失败"
echo "✅ 系统初始化完成"

# -------------------------- 模块2：安装OpenSSL 1.1.1w --------------------------
progress_msg "模块2/4：安装OpenSSL 1.1.1w"
cd || error_exit "切换到根目录失败"

# 2.1 下载并解压
wget -q https://gitee.com/jinze6762/openssl-resources/raw/master/openssl-1.1.1w.tar.gz || error_exit "OpenSSL源码下载失败"
tar xf openssl-1.1.1w.tar.gz >/dev/null 2>&1 || error_exit "OpenSSL源码解压失败"
cd openssl-1.1.1w || error_exit "进入OpenSSL目录失败"

# 2.2 编译安装（使用动态线程数$MAKE_JOBS）
./config shared --prefix=/usr/local/openssl --openssldir=/usr/local/openssl >/dev/null 2>&1 || error_exit "OpenSSL配置失败"
make -j$MAKE_JOBS >/dev/null 2>&1 || error_exit "OpenSSL编译失败（线程数：$MAKE_JOBS）"
make install >/dev/null 2>&1 || error_exit "OpenSSL安装失败"

# 2.3 替换系统旧版
mv /usr/bin/openssl /usr/bin/openssl.bak || error_exit "旧版OpenSSL备份失败"
ln -s /usr/local/openssl/bin/openssl /usr/bin/openssl || error_exit "OpenSSL软链接创建失败"
ln -s /usr/local/openssl/lib/libssl.so.1.1 /usr/lib/libssl.so.1.1 || error_exit "libssl软链接创建失败"
ln -s /usr/local/openssl/lib/libcrypto.so.1.1 /usr/lib/libcrypto.so.1.1 || error_exit "libcrypto软链接创建失败"

# 2.4 配置动态链接库
echo "/usr/local/lib64/" | tee -a /etc/ld.so.conf >/dev/null || error_exit "动态链接库路径配置失败"
ldconfig || error_exit "动态链接库加载失败"

# 2.5 验证
openssl_version=$(openssl version | awk '{print $2}')
echo "✅ OpenSSL版本：$openssl_version"
cd || error_exit "返回根目录失败"

# -------------------------- 模块3：安装Python 3.11.9 --------------------------
progress_msg "模块3/4：安装Python 3.11.9"
cd || error_exit "切换到根目录失败"

# 3.1 下载并解压
wget -q https://registry.npmmirror.com/-/binary/python/3.11.9/Python-3.11.9.tar.xz || error_exit "Python源码下载失败"
tar xf Python-3.11.9.tar.xz >/dev/null 2>&1 || error_exit "Python源码解压失败"
cd Python-3.11.9 || error_exit "进入Python目录失败"

# 3.2 编译安装（使用动态线程数$MAKE_JOBS，关联OpenSSL）
./configure prefix=/usr/local/python311 -C --with-openssl=/usr/local/openssl --with-openssl-rpath=auto >/dev/null 2>&1 || error_exit "Python配置失败"
make -j$MAKE_JOBS >/dev/null 2>&1 || error_exit "Python编译失败（线程数：$MAKE_JOBS）"
make install >/dev/null 2>&1 || error_exit "Python安装失败"

# 3.3 创建软链接
ln -s /usr/local/python311/bin/python3 /usr/bin/python3.11 || error_exit "Python软链接创建失败"
ln -s /usr/local/python311/bin/pip3 /usr/bin/pip3.11 || error_exit "pip软链接创建失败"

# 3.4 升级pip
python3.11 -m pip install --upgrade pip -q || error_exit "pip升级失败"

# 3.5 验证
python_version=$(python3.11 --version | awk '{print $2}')
echo "✅ Python版本：$python_version"
cd || error_exit "返回根目录失败"

# -------------------------- 模块4：安装MySQL 8.0 --------------------------
progress_msg "模块4/4：安装MySQL 8.0并配置"
cd || error_exit "切换到根目录失败"

# 4.1 下载并安装仓库
wget -q https://dev.mysql.com/get/mysql84-community-release-el7-1.noarch.rpm || error_exit "MySQL仓库包下载失败"
yum install -y mysql84-community-release-el7-1.noarch.rpm >/dev/null 2>&1 || error_exit "MySQL仓库安装失败"

# 4.2 安装MySQL服务
yum install -y mysql-community-server --nogpgcheck >/dev/null 2>&1 || error_exit "MySQL服务安装失败"

# 4.3 启动服务
systemctl start mysqld || error_exit "MySQL服务启动失败"
if ! systemctl is-active --quiet mysqld; then
    error_exit "MySQL服务启动后未正常运行"
fi
echo "✅ MySQL服务已启动"

# 4.4 获取临时密码
TEMP_PWD=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')
if [ -z "$TEMP_PWD" ]; then
    error_exit "无法获取MySQL临时密码"
fi

# 4.5 重置root密码
mysql -uroot -p"$TEMP_PWD" --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$ROOT_PWD';" >/dev/null 2>&1 || error_exit "root密码重置失败（请确认密码复杂度）"
echo "✅ MySQL root密码重置完成"

# 4.6 创建数据库和用户
mysql -uroot -p"$ROOT_PWD" -e "
CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` DEFAULT CHARSET utf8;
CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$USER_PWD';
CREATE USER IF NOT EXISTS '$DB_USER'@'%' IDENTIFIED BY '$USER_PWD';
GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'localhost' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
" >/dev/null 2>&1 || error_exit "MySQL数据库/用户创建失败"
echo "✅ MySQL数据库和用户配置完成"

# -------------------------- 部署完成 --------------------------
echo -e "\n============================================="
echo "🎉 服务器一键部署全部完成！"
echo -e "\n【已安装组件及版本】"
echo "1. GCC：$gcc_version"
echo "2. OpenSSL：$openssl_version"
echo "3. Python：$python_version（路径：/usr/bin/python3.11）"
echo "4. MySQL：8.0（服务已启动）"
echo -e "\n【部署环境信息】"
echo "CPU核心数：$CPU_CORES 核（编译线程数：$MAKE_JOBS）"
echo "交换内存：4GB（已启用，缓解小内存压力）"
echo -e "\n【MySQL关键信息】（请妥善保存）"
echo "1. root账号：root / $ROOT_PWD"
echo "2. 项目数据库：$DB_NAME"
echo "3. 项目账号：$DB_USER / $USER_PWD"
echo -e "\n【后续操作建议】"
echo "1. 清除命令行历史：history -c"
echo "2. 测试MySQL登录：mysql -uroot -p"
echo "3. 远程连接：用Navicat等工具，IP填服务器地址，账号用 $DB_USER"
echo "============================================="
